package com.github.sparkzxl.demo.infrastructure.component;

import com.alibaba.fastjson.JSONObject;
import com.github.sparkzxl.core.annotation.ResponseResult;
import com.github.sparkzxl.core.base.result.ApiResponseStatus;
import com.github.sparkzxl.core.context.BaseContextConstants;
import com.github.sparkzxl.core.context.BaseContextHandler;
import com.github.sparkzxl.core.entity.AuthUserInfo;
import com.github.sparkzxl.core.resource.SwaggerStaticResource;
import com.github.sparkzxl.core.support.SparkZxlExceptionAssert;
import com.github.sparkzxl.core.utils.ResponseResultUtils;
import com.github.sparkzxl.core.utils.StringHandlerUtils;
import com.github.sparkzxl.demo.infrastructure.constant.DemoConstant;
import com.nimbusds.jose.JWSObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * description: 权限访问拦截器
 *
 * @author charles.zhou
 * @date 2021-05-06 13:50:14
 */
@Component
public class PermissionInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //拦截器取到请求先进行判断，如果是OPTIONS请求，则放行
        if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
            System.out.println("Method:OPTIONS");
            return true;
        }
        if (StringHandlerUtils.isIgnore(SwaggerStaticResource.EXCLUDE_STATIC_PATTERNS, request.getRequestURI())) {
            return true;
        }
        // 请求拦截
        if (!StringHandlerUtils.isIgnore(DemoConstant.ignoreUrls, request.getRequestURI())) {
            // 获取token
            String accessToken = ResponseResultUtils.getAuthHeader(request);
            if (StringUtils.isEmpty(accessToken)) {
                SparkZxlExceptionAssert.businessFail(ApiResponseStatus.UN_AUTHORIZED);
            }
            // 解析token信息
            JWSObject jwsObject = JWSObject.parse(accessToken);
            String payload = jwsObject.getPayload().toString();
            AuthUserInfo authUserInfo = JSONObject.parseObject(payload, AuthUserInfo.class);
            //设置当前请求线程全局信息
            BaseContextHandler.setUserId(authUserInfo.getId());
            BaseContextHandler.setAccount(authUserInfo.getAccount());
            BaseContextHandler.setName(authUserInfo.getName());
        }
        if (handler instanceof HandlerMethod) {
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            final Class<?> classz = handlerMethod.getBeanType();
            final Method method = handlerMethod.getMethod();
            if (classz.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(BaseContextConstants.RESPONSE_RESULT_ANN, classz.getAnnotation(ResponseResult.class));
            } else if (method.isAnnotationPresent(ResponseResult.class)) {
                request.setAttribute(BaseContextConstants.RESPONSE_RESULT_ANN, method.getAnnotation(ResponseResult.class));
            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        super.afterCompletion(request, response, handler, ex);
    }

}
